/**
 * Project  : monkey
 * Author   : Wu Tian Qiang
 * Date     : 2016/10/18 20:49:30
 */
Ext.define('Monkey.view.user.UserController', {
    extend: 'Monkey.view.BaseController',
    alias: 'controller.ctrl-user',

    reloadUser: function () {
        var references = Ext.getCmp('mk-user').getReferences();
        references.account.setValue('');
        references.email.setValue('');
        references.mobile.setValue('');
        var store = Ext.getCmp('userGrid').getStore();
        store.loadPage(1, {
            params: {}
        });
    },

    //显示新增窗口
    addUser: function () {
        var window = Ext.create('Monkey.view.user.UserWindow');
        window.setTitle('新增用户');
        window.setIconCls('user-add');
        window.getViewModel().data.isAdd = true;
        window.show();
    },

    //显示修改窗口
    modifyUser: function (record) {
        if (Ext.isEmpty(record.data)) {
            var userGrid = this.getReferences().userGrid;
            var records = userGrid.getSelectionModel().getSelection();
            if (records.length == 0) {
                Ext.Msg.show({
                    title: '提示',
                    message: '请先选中需要修改的用户',
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR
                });
                return;
            }
            record = records[0];
        }

        var window = Ext.create('Monkey.view.user.UserWindow');
        window.setTitle('修改用户');
        window.setIconCls('user-edit');

        var form = window.down('form');
        var password = window.down('textfield[inputType="password"]');
        console.log(record);
        form.remove(password);

        var viewModel = window.getViewModel();
        viewModel.data.isAdd = false;
        viewModel.setModelData(record.data);

        setTimeout(function () {
            var treepicker = window.down('treepicker');
            treepicker.setValue(record.data.orgId);
        }, 500);

        window.show();
    },

    rowdblclick: function (node, record) {
        this.modifyUser(record);
    },

    ok: function () {
        var view = this.getView(),
            viewModel = this.getViewModel(),
            method = 'PUT',
            me = this;
        viewModel.data.orgId = view.down('treepicker').getValue();
        var form = view.getReferences().form;
        if (!form.isValid()) {
            return;
        }
        if (viewModel.data.isAdd) {
            method = 'POST';
        }
        console.log(viewModel.data);
        console.log(Ext.encode(viewModel.data));
        this.request(Monkey.URL.SERVER_URL + '/m/user.json', method, viewModel.data, function (data) {
            console.log(data);
            var icon = Ext.Msg.ERROR;
            if (data.success) {
                view.close();
                me.reloadUser();
                icon = Ext.Msg.INFO;
            }
            Ext.Msg.show({
                title: '提示',
                message: data.message,
                buttons: Ext.Msg.OK,
                icon: icon
            });
        });
    },

    cancel: function () {
        this.getView().close();
    },

    renderStatus: function (data) {
        return data == 'NORMAL' ? '正常状态' : '禁用状态';
    },

    renderSex: function (data) {
        return data == 'MAN' ? '男' : '女';
    },

    //查询按钮相应事件
    findUser: function () {
        var references = this.getReferences();
        var account = references.account.getValue();
        var email = references.email.getValue();
        var mobile = references.mobile.getValue();
        var store = Ext.getCmp('userGrid').getStore();
        store.loadPage(1, {
            params: {
                'search.account_like': account,
                'search.email_like': email,
                'search.mobile_like': mobile
            }
        });
    },

    findUserByOrg: function (cmp, record) {
        console.log(record);
        var store = Ext.getCmp('userGrid').getStore();
        store.loadPage(1, {
            url: Monkey.URL.SERVER_URL + '/m/user/organization/' + record.data.id + '.json'
        });
    },

    restPasswd: function () {
        var userGrid = this.getReferences().userGrid;
        var records = userGrid.getSelectionModel().getSelection();
        if (records.length == 0) {
            Ext.Msg.show({
                title: '提示',
                message: '请先选中需要重置密码的用户',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }
        var record = records[0];

        var window = Ext.create('Monkey.view.user.RestPasswdWindow');
        window.setTitle('重置密码（昵称：' + record.data.nick + '）');
        var form = window.down('form');
        console.log(record);
        form.down('hidden[name="userId"]').setValue(record.data.id);
        window.show();
    },

    restPasswdOK: function () {
        var me = this,
            view = me.getView(),
            form = view.down('form'),
            userId = form.down('hidden[name="userId"]'),
            newPwd = form.down('textfield[name="newPwd"]'),
            newPwd2 = form.down('textfield[name="newPwd2"]');

        this.request(Monkey.URL.SERVER_URL + '/m/user/rest/passwd.json', 'PUT',
            {userId: userId.getValue(), newPwd: newPwd.getValue(), newPwd2: newPwd2.getValue()},
            function (data) {
                console.log(data);
                var icon = Ext.Msg.ERROR;
                if (data.success) {
                    view.close();
                    icon = Ext.Msg.INFO;
                }
                Ext.Msg.show({
                    title: '提示',
                    message: data.message,
                    buttons: Ext.Msg.OK,
                    icon: icon
                });
            });
    },

    lockUser: function () {
        this.changeStatusWin('封锁用户', 'BLOCKED');
    },

    unlockUser: function () {
        this.changeStatusWin('解封用户', 'NORMAL');
    },

    changeStatusWin: function (title, status) {
        var userGrid = this.getReferences().userGrid;
        var records = userGrid.getSelectionModel().getSelection();
        if (records.length == 0) {
            Ext.Msg.show({
                title: '提示',
                message: '请先选中需要改变状态的用户',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }

        var ids = Monkey.Utils.arrayModelToString(records, 'id', ',');
        var window = Ext.create('Monkey.view.user.ChangeStatusWindow');
        window.setTitle(title);
        var form = window.down('form');
        form.down('hidden[name="userIds"]').setValue(ids);
        form.down('hidden[name="status"]').setValue(status);

        window.show();
    },

    changeStatusOK: function () {
        var me = this,
            view = me.getView(),
            form = view.down('form');

        this.request(Monkey.URL.SERVER_URL + '/m/user/status.json', 'PUT', {
                ids: form.down('hidden[name="userIds"]').getValue(),
                reason: form.down('textareafield[name="reason"]').getValue(),
                status: form.down('hidden[name="status"]').getValue()
            },
            function (data) {
                var icon = Ext.Msg.ERROR;
                if (data.success) {
                    view.close();
                    icon = Ext.Msg.INFO;
                    me.reloadUser();
                }
                Ext.Msg.show({
                    title: '提示',
                    message: data.message,
                    buttons: Ext.Msg.OK,
                    icon: icon
                });
            });
    },

    viewStatusHistory: function () {
        var userGrid = this.getReferences().userGrid;
        var records = userGrid.getSelectionModel().getSelection();
        if (records.length == 0) {
            Ext.Msg.show({
                title: '提示',
                message: '请先选中需要查看的用户',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }
        var record = records[0];
        var window = Ext.create('Monkey.view.user.StatusHistoryWindow', {
            userId: record.data.id,
            nick: record.data.nick
        });
        window.show();
    },

    showGrantWin: function (cmp) {
        var record = cmp.getWidgetRecord();
        Ext.create('Monkey.view.user.GrantRolePermissionWindow', {
            title: '给用户授权(昵称：' + record.data.nick + ')',
            userId: record.data.id
        }).show();
    },

    viewPermission: function () {
        var userGrid = this.getReferences().userGrid;
        var records = userGrid.getSelectionModel().getSelection();
        if (records.length == 0) {
            Ext.Msg.show({
                title: '提示',
                message: '请先选中需要查看的用户',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }
        var record = records[0];
        Ext.create('Monkey.view.user.ViewUserPermissionWindow', {
            userId: record.data.id,
            icon: 'resources/icons/16/eye.png',
            title: '查看已分配的权限(昵称：' + record.data.nick + ')'
        }).show();
    }

});
